package com.stellar.circle.interceptor;


import com.stellar.core.context.LoginContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Jqchan_
 * Feign 请求拦截器
 */
@Component
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String loginId = request.getHeader(LoginContextHolder.LOGIN_USER_HEADER);
        if (StringUtils.isNotBlank(loginId)) {
            requestTemplate.header(LoginContextHolder.LOGIN_USER_HEADER, loginId);
        }
        String role = request.getHeader(LoginContextHolder.LOGIN_USER_ROLE_HEADER);
        if (StringUtils.isNotBlank(role)) {
            requestTemplate.header(LoginContextHolder.LOGIN_USER_ROLE_HEADER, role);
        }
        String openid = request.getHeader(LoginContextHolder.MINI_APP_LOGIN_USER_HEADER);
        if (StringUtils.isNotBlank(openid)) {
            requestTemplate.header(LoginContextHolder.MINI_APP_LOGIN_USER_HEADER, openid);
        }
    }
}
